/**
 * Created by DevilsEyes on 2016/3/22.
 */
'use strict';

define(['text!components/logger/tmp.html', 'page', 'template', 'timer', 'layer', 'jquery', 'ex'], function (page, Page, template, timer, layer, $, ex) {

    var vm = null;
    var render = template.compile(page);

    //存储回调事件或者调用时的参数
    var After_Login_Callback = null;
    var symbol = {};
    var apiList = {
        getCaptcha: api + 'user/registerCaptcha',
        login: api + 'user/register',
        loginByCode: api + 'wx/loginInfoByCode',
        loginByOpenId: api + 'wx/loginInfoByOpenId',
        refresh: api + 'login'
    };

    var close;

    vm = new Page.creat({
        $id: 'logger',
        $model: {
            $: {},

            data: {},
            init: function () {
                var $log = $('#logger').html(render({close: close}));
                symbol.show = true;
                //重置数据
                logger.data = {
                    tel: '',
                    captcha: ''
                };

                vm.bind$(vm.$, $log);
                vm.bindEvent(vm.event, $log);
                //进入动画
                {

                    var dialog = {
                        $: vm.$.logBody,
                        w: db.w - 60,
                        h: vm.$.logBody.height()
                    };
                    dialog.$.css({
                        top: (db.h - dialog.h) / 2,
                        left: (db.w - dialog.w) / 2,
                        width: dialog.w,
                        height: 0
                    });
                    vm.$.logShade.css({
                        opacity: 0
                    });
                    ex.async(function () {
                        vm.$.logShade.css({
                            opacity: 1
                        });
                        dialog.$.css({
                            height: dialog.h
                        });
                    });
                    ex.async(function () {
                        dialog.$.find('div').css({
                            opacity: 1
                        });
                    }, 200);
                }
            },
            event: {
                close: function () {

                    //防止动画冲突
                    if (symbol.close)return;
                    symbol.close = true;

                    //淡出动画
                    vm.$.logShade.css({
                        opacity: 0
                    });
                    vm.$.logBody.find('div').css({
                        opacity: 0
                    });
                    ex.async(function () {
                        vm.$.logBody.css({
                            height: 0
                        });
                    }, 100);
                    ex.async(function () {
                        $('#logger').html('');
                        symbol.close = false;
                        symbol.show = false;
                        //350ms,解决点击穿透
                    }, 350);


                },
                vecStatusCheck: function () {
                    logger.data.tel = vm.$.tel.val();
                    if (logger.data.tel.length == 11 && !symbol.vec) {
                        vm.$.getvec.removeClass('un');
                    } else {
                        vm.$.getvec.addClass('un');
                    }
                    vm.event.btnStatusCheck();
                },
                btnStatusCheck: function () {
                    logger.data.captcha = vm.$.captcha.val();
                    if (logger.data.tel.length == 11 && logger.data.captcha.length == 6) {
                        vm.$.loginbtn.removeClass('un');
                    } else {
                        vm.$.loginbtn.addClass('un');
                    }
                },
                getCaptcha: function () {
                    if (symbol.vec || vm.$.getvec.hasClass('un'))return;
                    symbol.vec = true;
                    ex.jsonp({
                        url: apiList.getCaptcha,
                        data: {
                            phone: logger.data.tel
                        },
                        success: function (obj) {
                            if (obj.code != 0) {
                                layer.msg(obj.msg);
                                symbol.vec = false;
                            } else {
                                vm.$.getvec.addClass('un');
                                vm.$.getvec.text('剩余 60 秒');
                                var t = timer.register(vm.$.getvec, function (time) {

                                    var dt = 60 - Math.floor((time - this.creatTime) / 1000);
                                    if (dt > 0) {
                                        this.$dom.text('剩余 ' + dt + ' 秒');
                                    } else {
                                        symbol.vec = false;
                                        this.$dom.text('获取验证码');
                                        this.$dom.removeClass('un');
                                        timer.logout(t);
                                    }
                                });
                            }
                        }
                    })
                },
                login: function () {
                    if (vm.$.loginbtn.hasClass('un'))return;
                    ex.jsonp({
                        url: apiList.login,
                        method: 'POST',
                        data: {
                            openId: db.wx_openId,
                            phone: logger.data.tel,
                            captcha: logger.data.captcha
                        },
                        success: function (obj) {
                            if (obj.code != 0) {
                                logger.isLogin = true;

                                db.set('userInfo', obj.data);
                                layer.msg('登录成功!');
                            } else {
                                obj = obj.data;
                                logger.close();
                                After_Login_Callback();
                            }
                        }
                    })

                }

            }
        }
    });

    var logger = {

        check: false,
        isLogin: false,

        login: function (object) {
            close = object.close || false;
            if (typeof object.callback == 'function')After_Login_Callback = object.callback;
            if (this.check) {
                //登录流程已验证，未登录
                vm.init();

            } else {
                //登录流程未验证
                After_Login_Callback = object;
            }
        },
        promise: new Promise(),
        close: function () {
            if (symbol.show) {
                vm.event.close();
            }
        }

    };

    //登录状态验证完毕
    function done() {
        logger.check = true;
        if (After_Login_Callback != null && typeof After_Login_Callback == 'object') {
            logger.login(After_Login_Callback)
        }
    }

    ex.jsonp({
        url: apiList.refresh,
        success: function (obj) {
            if (obj.code == 0) {
                var data = {user: obj.data};

                if (data.user) {
                    logger.isLogin = true;
                    db.set('userInfo', data.user);
                    logger.promise.resolve();
                }
            } else
                codeOrOpenIdLogin();
        }
    });

    function codeOrOpenIdLogin() {
        //初始化
        if (agent.isWechat) {

            if (db.wx_openId) {
                ex.jsonp({
                    url: apiList.loginByOpenId,
                    data: {
                        openId: db.wx_openId
                    },
                    success: function (obj) {
                        if (obj.code == 0) {
                            var data = obj.data;
                            if (data.user) {
                                logger.isLogin = true;
                                db.set('userInfo', data.user);
                                logger.promise.resolve();
                            } else {
                                logger.promise.reject();
                            }
                            done();
                        }
                    }
                })
            } else if (db.wx_code) {
                ex.jsonp({
                    url: apiList.loginByCode,
                    data: {
                        code: db.wx_code
                    },
                    success: function (obj) {
                        if (obj.code == 0) {
                            var data = obj.data;
                            if (data.user) {
                                logger.isLogin = true;
                                db.set('userInfo', data.user);
                                logger.promise.resolve();
                            } else {
                                logger.promise.reject();
                            }
                            document.cookie = 'openId=' + data.openId;
                            db.wx_openId = data.openId;
                            done();
                        }
                    }
                })
            }

        } else if (agent.isClient) {
            //todo 凭借手机号调取登录接口
        } else {
            logger.promise.reject();
            done();
        }
    }

    return logger;
});